const { app, BrowserWindow, desktopCapturer } = require('electron');
const path = require('path');
const moment = require('moment');

/*
const getIp = () => {
  let os = require('os'),
    iptable = {},
    ifaces = os.networkInterfaces()
  for (let dev in ifaces) {
    ifaces[dev].forEach(function (details, alias) {
      if (details.family == 'IPv4') {
        iptable[dev + (alias ? ':' + alias : '')] = details.address
      }
    })
  }

  for (let key in iptable) {
    return iptable[key]
  }
}
*/
const getIp = () => {
  let ip1 = ""
  let ip2 = ""
  let hotspot = false
  let os = require('os'),
  iptable = {},
  ifaces = os.networkInterfaces()
  for (let dev in ifaces) {
    ifaces[dev].forEach(function (details, alias) {
      if (details.family == 'IPv4' && details.address.substring(0, 10) == "192.168.12") {
        //iptable[dev + (alias ? ':' + alias : '')] = details.address
        //return details.address;
        hotspot = true;
        ip1 = details.address;
      }
      if (details.family == 'IPv4' && details.address.substring(0, 3) == "192") {
        //iptable[dev + (alias ? ':' + alias : '')] = details.address
        //return details.address;
        ip2 = details.address;
      }
    })
  }

  /*
  for (let key in iptable) {
    return iptable[key]
  }
  */
 if (hotspot) return ip1;
 return ip2;
}

/*
//https://blog.csdn.net/qq_43576028/article/details/122384426
//
const ipcMain = require('electron').ipcMain;
  
ipcMain.on('test1', function(event, arg) {
	console.log(arg);  // prints "我是渲染进程的test2"
	event.sender.send('test2', '我是主进程的test1');

});
*/
const ipcMain = require('electron').ipcMain;

ipcMain.on('test3', function(event, arg) {
	console.log(arg);  // prints "我是渲染进程"
	event.returnValue = '我是主进程'; 
  /*
  var http = require('http');

  var server = http.createServer(function(req, res){
      console.log('客户端请求url：' + req.url);
      console.log('http版本：' + req.httpVersion);
      console.log('http请求方法：' + req.method);

      res.end('ok');
  });

  server.listen(4443);
  */
});

let mainWindow;


// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}


//https://blog.csdn.net/baidu_30907803/article/details/115449205
app.on('certificate-error', (event, _webContents, _url, _error, _certificate, callback) => {
  //if (url === 'https://github.com') {
  //if (url === 'https://192.168.1.236:6443') {
    // Verification logic.
  event.preventDefault()
  callback(true)
  //} else {
  //  callback(false)
  //}
})

//const createWindow = async () => {
const createWindow = () => {
  // Create the browser window.
  //const mainWindow = new BrowserWindow({
    mainWindow = new BrowserWindow({
    width: 1920,
    height: 1080,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true,
      contextIsolation: false
    },
  });


  mainWindow.webContents.on("did-finish-load",()=> {
    //console.log("did-finish-load");
  })
  
  
  
  mainWindow.webContents.on("dom-ready",()=>{
    //console.log("dom-ready");
  })

  mainWindow.webContents.on("page-title-updated",()=>{
    desktopCapturer.getSources({ types: ['screen'] }).then(async sources => {
      for (const source of sources) {
	  mainWindow.webContents.send('SET_AUDIO', false)
	  //mainWindow.webContents.send('SET_SOURCE', source.id)
	  mainWindow.webContents.send('startTimer', source.id)
	  recInterval = setInterval(funInterval, 1000 * 60)

	  return
      }
    })
  })

  let localIP = getIp();
  //console.log(localIP);

  // and load the index.html of the app.
  //mainWindow.loadFile(path.join(__dirname, 'index.html'));
  //mainWindow.loadURL('https://' + localIP + ':6443');
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  
  mainWindow.removeMenu();


  // Open the DevTools.
  mainWindow.webContents.openDevTools();


};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.

let recT = false;
let recInterval;


const funInterval = async () => {
  mainWindow.webContents.send('startTimer', "");
}


///*
const createHttpServer = async () => {
  var http = require('http');

  var server = http.createServer(function(req, res){
      //console.log('客户端请求url：' + req.url);
      //console.log('http版本：' + req.httpVersion);
      //console.log('http请求方法：' + req.method);
      //console.log('............');

      if (req.url == "/startRec") {
        mainWindow.webContents.send('startRec', "")
        //console.log('客户端请求url：' + req.url);
      }

      if (req.url == "/stopRec") {
        mainWindow.webContents.send('stopRec', "")
        //console.log('客户端请求url：' + req.url);
      }

      if (req.url == "/startTimer") {
        if (!recT) {
          recT = true;
        } else {
          const date = new Date();
          //const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
          const formattedDate = moment(date).format('YYYY-MM-DD-HH-mm-ss');
          res.end("started:" + formattedDate);
          return;
        }
        mainWindow.webContents.send('startTimer', "")
        recInterval = setInterval(funInterval, 1000 * 600)
        //recInterval = setInterval(funInterval, 1000 * 60)
      }

      if (req.url == "/stopAll") {
        recT = false;
        clearInterval(recInterval);
        mainWindow.webContents.send('stopAll', "");
      }

      //res.end('ok');

      const date = new Date();
      //const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
      const formattedDate = moment(date).format('YYYY-MM-DD-HH-mm-ss');
      res.end(formattedDate);
  });

  server.listen(4443);
}

createHttpServer();
//*/
